/**
 * Created by yunpeng on 2014/12/4.
 */
var lid=null;
var usertype=1;//用户类型
$('#busDg').datagrid({
    url:'/lifeService/lifeServiceList',
    //border : false,
    rownumbers: true,
    idField : 'lid',
    pagination : true,
    sortName : 'createtime',//默认排序的列
    sortOrder: 'desc',
    pageSize : 10,
    pageList : [ 10, 20, 40, 80 ],
    fitColumns : true,
    fit : true,
    checkOnSelect : false,
    selectOnCheck : true,
    striped: true,//条纹交替
    columns:[[
        {field:'',checkbox:true},
        /*{field:'lid',title:'序号',width:50},*/
        {field:'lname',title:'商家名称',width:200,align:'center'},
        {field:'lprice',title:'价格',width:100,align:'center'},
        {field:'serv_name',title:'服务类型',width:100,align:'center'},
        {field:'province',title:'省份',width:100,align:'center'},
        {field:'city',title:'所属城市',width:100,align:'center'},
        {field:'phone',title:'联系电话',width:100,align:'center'},
        {field:'address',title:'详细地址',width:200,align:'center'},
        {field:'describe',title:'商家信息',width:300,align:'center'},
        {field:'createtime',title:'创建时间',width:200,align:'center'
            /*formatter : function(value, rowData, rowIndex) {
            //return rowData.flgcxxbqxj.tbrq;
            var unixTimestamp = new Date(new Date(value).getDate().format("yyyy-MM-dd hh:mm:ss");///格式化时间到小时
            return unixTimestamp;

        }*/},
        {field:'recommend',title:'首页推荐',width:200,align:'center',
            formatter: function(value,row,index){
                var val = '否';
                if(value=='0'){
                    val = '是';
                }
                return val;
            }}
    ]],
    toolbar : '#tb'
    /*[ {
        text : '新增商家',
        handler : function() {
            addBus();
        },
        iconCls : 'icon-add'
    }, {
        text : '编辑',
        handler : function() {
            editBus();
        },
        iconCls : 'icon-edit'
    },{
        text : '删除商家',
        handler : function() {
            delBus();
        },
        iconCls : 'icon-remove'
    } ]*/
});


function searchBusList(){
    $('#busDg').datagrid('load',{
        busDate1: $('#busDate1').datebox('getValue'),
        busDate2: $('#busDate2').datebox('getValue'),
        busName: $('#busName').textbox('getValue')
    });
}

function delBus(){
    var rows = $('#busDg').datagrid('getChecked');
    if (rows.length > 0) {
        $.messager.confirm('确认', '是否删除勾选的商家？', function(b) {
            if (b) {
                var ids = [];
                for ( var i = 0; i < rows.length; i++) {
                    ids.push(rows[i].lid);
                }
                $.ajax({
                    url : '/auth/lifeService/delBus',
                    data : {
                        ids : ids.join()
                    },
                    type:'POST',
                    dataType : 'json',
                    success : function(data) {
                        if(data==true){
                            $('#busDg').datagrid('reload');
                            $('#busDg').datagrid('uncheckAll');// 取消选中的所有记录
                            showMsg('删除成功！');
                        }else{
                            showMsg('删除失败！');
                        }
                    }
                });
            }
        });

    } else {
        $.messager.alert('提示', '请勾选要删除的商家。', 'error');
    }
}

function editBus(){//编辑商家信息
    var rows = $('#busDg').datagrid('getChecked');
    if (rows.length == 1) {
        //动态加载
        var editBusWindow = $('<div/>')
            .dialog(
            {
                width : 640,
                height : 520,
                href : '../lifeService/lifeEdit.html',
                modal : true,
                title : '编辑商家信息',
                maximizable:true,
                cache:false,
                minimized:true,
                buttons : [{
                    text : '取&nbsp;&nbsp;消',
                    width : 60,
                        handler : function() {
                            editBusWindow.dialog('close');
                        }
                    },
                    {
                        text : '保&nbsp;&nbsp;存',
                        width : 60,
                        handler : function() {
                            $('#editBus').form('submit', {
                                url:'/auth/lifeService/editBus',
                                onSubmit: function(){
                                    // 做一些检查
                                    // 返回false可以阻止提交操作；
                                },
                                success:function(data){
                                    if(data=='true'){
                                        editBusWindow.dialog('close');
                                        $('#busDg').datagrid('load');
                                        showMsg('修改成功！');
                                    }else{
                                        showMsg('修改失败！');
                                    }
                                }
                            });
                        }
                    } ],
                onClose : function() {
                    $('#busDg').datagrid('uncheckAll');// 取消选中的所有记录
                    $(this).dialog('destroy');//动态加载一定要销毁
                },
                //加载数据，用onLoad，不是用onOpen
                onLoad : function() {
                    $('#editBus').form('load', rows[0]);
                    $('#serv_id').combobox('setValue',rows[0].stypeid);//设置下拉列表的值
                    $('#cid').combobox('select',rows[0].cid);
                    $('#filePath').filebox({
                        buttonText: '请选择',
                        buttonAlign: 'right'
                    });
                    showMap();//显示地图
                    //显示商家图片
                    $('#imgs').html('<img src="data:image/png;base64,'+rows[0].pic+'" style="width:100px;height:100px;vertical-align: middle;margin-top: -19px;">&nbsp;&nbsp;(保存后更改)');
                }
            });
    } else {
        $.messager.alert('提示', '请选择1条记录', 'error');
    }
}


function addBus(){//添加商家
    var addWindow = $('<div/>').dialog({
        width : 640,
        height : 520,
        href : '../lifeService/lifeAdd.html',
        modal : true,
        title : '新增商家',
        //minimizable:true,
        maximizable:true,
        cache:false,
        minimized:true,
        buttons : [ {
            text : '取&nbsp;&nbsp;消',
            width : 60,
            handler : function() {
                addWindow.dialog('close');
            }
        }, {
            text : '保&nbsp;&nbsp;存',
            width : 60,
            handler : function() {
                $('#addBus').form('submit', {
                    url:'/auth/lifeService/addBus',
                    onSubmit: function(){
                            // 做一些检查
                            // 返回false可以阻止提交操作；
                    },
                    success:function(data){
                        if(data=='true'){
                            addWindow.dialog('close');
                            $('#busDg').datagrid('load');
                            showMsg('添加成功！');
                        }else{
                            showMsg('添加失败！');
                        }
                    }
                });

            }
        } ],
        onLoad : function(){
            $('#filePath').filebox({
                buttonText: '请选择',
                buttonAlign: 'right'
            });
            showMap();

        },
        onClose : function() {
            $(this).dialog('destroy');//动态加载一定要销毁
        }
    });

}

function showMsg(msg){
    $.messager.show({
        title:'提示',
        msg:msg,
        timeout:2000,
        showType:'fade'
    });

}

var map;
function showMap(){
    // 百度地图API功能
    map= new BMap.Map("container");
    map.centerAndZoom(new BMap.Point(119.13907,36.699503), 11);
    map.setCurrentCity("潍坊");
    //localSearch(map);
    //map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
    // 添加带有定位的导航控件
    map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
    map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
    map.enableAutoResize();
    // 添加带有定位的导航控件
    var navigationControl = new BMap.NavigationControl({
        // 靠左上角位置
        anchor: BMAP_ANCHOR_TOP_LEFT,
        // LARGE类型
        type: BMAP_NAVIGATION_CONTROL_LARGE,
        // 启用显示定位
        enableGeolocation: true
    });
    map.addControl(navigationControl);
    // 添加定位控件
    var geolocationControl = new BMap.GeolocationControl();
    geolocationControl.addEventListener("locationSuccess", function(e){
        // 定位成功事件
        var address = '';
        address += e.addressComponent.province;
        address += e.addressComponent.city;
        address += e.addressComponent.district;
        address += e.addressComponent.street;
        address += e.addressComponent.streetNumber;
        alert("当前定位地址为：" + address);
    });
    geolocationControl.addEventListener("locationError",function(e){
        // 定位失败事件
        alert(e.message);
    });
    map.addControl(geolocationControl);


    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            map.panTo(r.point);
            //alert('您的位置：'+r.address.city+' '+r.point.lng+','+r.point.lat);
        }
        else {
            alert('failed'+this.getStatus());
        }
    },{enableHighAccuracy: true})

    //单击获取点击的经纬度和城市名称
    var geoc = new BMap.Geocoder();
    map.addEventListener("click",function(e){
        //$('#coords').val(e.point.lng + "," + e.point.lat);
        $('#coords').textbox('setValue',e.point.lng + "," + e.point.lat);//设置文本框的值
        /*var pt = e.point;
        geoc.getLocation(pt, function(rs){
            var addComp = rs.addressComponents;
            $('#city').val(addComp.city);
        });*/
    });

}


//以下是输入提示用到的，暂时未调用
function G(id) {
    return document.getElementById(id);
}

function localSearch(map){
    //关键字提示输入
    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
        {"input" : "suggestId"
            ,"location" : map
        });

    ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        G("searchResultPanel").innerHTML = str;
    });
    var myValue;
    ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
        G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });
}

function setPlace(){
    map.clearOverlays();    //清除地图上所有覆盖物
    function myFun(){
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        map.addOverlay(new BMap.Marker(pp));    //添加标注
    }
    var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
    });
    local.search(myValue);
}



$.extend($.fn.validatebox.defaults.rules,{
    usernames:{
        validator:function(value, param){
            var reg = /^[a-zA-Z]\w{5,29}$/;
            return reg.test(value);
        },
        message:'用户名格式不正确'
    },
    phones:{
        validator:function(value, param){
            var reg = /^1\d{10}$/;
            return reg.test(value);
        },
        message:'请输入正确的手机号'
    }
})

function viewOrder(){
    var rows = $('#busDg').datagrid('getChecked');
    if (rows.length == 1) {
        lid = rows[0].lid;
        //动态加载
        var editBusWindow = $('<div/>')
            .dialog(
            {
                width : document.body.clientWidth,
                height : document.body.clientHeight,
                href : '../lifeService/lifeOrders.html',
                modal : true,
                title : '查看商家订单记录',
                maximizable:true,
                cache:false,
                minimized:true,
                buttons : [{
                    text : '关&nbsp;&nbsp;闭',
                    width : 60,
                    handler : function() {
                        editBusWindow.dialog('close');
                    }
                }],
                onClose : function() {
                    $('#busDg').datagrid('uncheckAll');// 取消选中的所有记录
                    $(this).dialog('destroy');//动态加载一定要销毁
                },
                //加载数据，用onLoad，不是用onOpen
                onLoad : function() {

                }
            });
    } else {
        $.messager.alert('提示', '请选择1条记录', 'error');
    }
}